<template>
  <div class="step1">
    <h2 v-if="!ifStep2">
      {{
        $t(
          `breach.steps.step1.content.title.${
            breachMode === 1 ? "breach" : "dlp"
          }`
        )
      }}
    </h2>
    <a-form :form="form">
      <a-form-item :label="$t('breach.steps.step1.content.form.describe')">
        <a-input
          :placeholder="
            $t('breach.steps.step1.content.form.describe.placeholder')
          "
          v-decorator="[
            'EventShortDescription',
            {
              rules: [
                {
                  required: true,
                  message: $t(
                    'breach.steps.step1.content.form.describe.placeholder'
                  ),
                },
              ],
            },
          ]"
          :maxLength="100"
          :disabled="!ifCanEdit"
        ></a-input>
      </a-form-item>
      <a-form-item :label="$t('breach.steps.step1.content.form.detail')">
        <a-textarea
          rows="5"
          :placeholder="
            $t('breach.steps.step1.content.form.detail.placeholder')
          "
          v-decorator="[
            'EventDetailDescription',
            {
              rules: [
                {
                  required: true,
                  message: $t('breach.steps.step1.content.form.tip'),
                },
              ],
            },
          ]"
          :disabled="!ifCanEdit"
        ></a-textarea>
      </a-form-item>
      <a-row :gutter="24" v-if="ifDispatch">
        <a-col :span="12">
          <a-form-item :label="$t('breach.steps.step1.content.form.type')">
            <a-select
              v-decorator="[
                'EventType',
                {
                  rules: [
                    {
                      required: true,
                      message: $t('breach.steps.step1.content.form.tip1'),
                    },
                  ],
                },
              ]"
              :placeholder="$t('breach.steps.step1.content.form.tip1')"
              :disabled="!ifCanEdit"
            >
              <a-select-option v-for="item in typeList" :key="item.value">{{
                $t(item.label)
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label="$t('breach.list.content.table.where')">
            <a-select
              v-decorator="['EventDestination']"
              :placeholder="$t('breach.steps.step1.content.form.tip1')"
              :disabled="!ifCanEdit"
              @change="(value) => (EventDestination = value)"
            >
              <a-select-option v-for="item in whereList" :key="item.value">{{
                $t(item.label)
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-if="ifDispatch && EventDestination === 6">
        <a-col :span="12">
          <a-form-item :label="$t('breach.list.content.table.where.other')">
            <a-input
              v-decorator="[
                'EventDestinationOther',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        'breach.steps.step1.content.form.way.other.placeholder'
                      ),
                    },
                  ],
                },
              ]"
              :placeholder="
                $t('breach.steps.step1.content.form.way.other.placeholder')
              "
              :disabled="!ifCanEdit"
            ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12" v-if="breachMode !== 1 || ifDispatch">
          <a-form-item :label="$t('breach.steps.step1.content.form.starttime')">
            <a-date-picker
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="$t('user.verification-code.required111566157')"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              v-decorator="[
                'EventOccurrenceTime',
                {
                  rules: [
                    {
                      required: true,
                      message: $t('breach.steps.step1.content.form.tip1'),
                    },
                  ],
                },
              ]"
              :disabled="!ifCanEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label="$t('breach.steps.step1.content.form.findtime')">
            <a-date-picker
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="$t('user.verification-code.required111566157')"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              v-decorator="[
                'EventFindTime',
                {
                  rules: [
                    {
                      required: true,
                      message: $t('breach.steps.step1.content.form.tip1'),
                    },
                  ],
                },
              ]"
              :disabled="!ifCanEdit"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <step-1-dlp
        ref="step1Dlp"
        v-if="breachMode !== 1"
        :ifCanEdit="ifCanEdit"
        :initData="breachDetail?.SupplementDetail"
      />
      <a-form-item :label="$t('breach.steps.step1.content.form.upload')">
        <upload-file
          ref="uploadFile"
          :breachId="breachDetail?.Id"
          :tip="$t('breach.steps.step1.content.form.file.tip')"
          :disabled="!ifCanEdit"
        />
      </a-form-item>
      <template v-if="ifDispatch && !ifStep2">
        <a-form-item
          :label="$t('breach.steps.step1.content.form.ifclose')"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 9 }"
          labelAlign="left"
        >
          <a-radio-group
            v-decorator="[
              'EventClose',
              {
                initialValue: 2,
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step1.content.form.tip1'),
                  },
                ],
              },
            ]"
            :disabled="!ifCanEdit"
            @change="(e) => (ifClose = e.target.value === 1)"
          >
            <a-radio :value="1">{{
              $t("user.verification-code.requiredLuck11yes")
            }}</a-radio>
            <a-radio :value="2">{{
              $t("user.verification-code.requiredLuck11no")
            }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="!ifClose"
          :label="$t('breach.steps.step1.content.form.selectower')"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 9 }"
          labelAlign="left"
        >
          <a-select
            v-decorator="[
              'EventProcessed',
              {
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step1.content.form.selectower'),
                  },
                ],
              },
            ]"
            show-search
            :placeholder="$t('breach.steps.step1.content.form.selectower')"
            :disabled="!ifCanEdit"
            option-filter-prop="children"
          >
            <a-select-option v-for="item in handlerList" :key="item.value">{{
              $t(item.label)
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-else
          :label="$t('breach.steps.step1.content.form.reason')"
        >
          <a-textarea
            rows="4"
            :placeholder="$t('breach.steps.step1.content.form.reason')"
            v-decorator="[
              'EventReason',
              {
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step1.content.form.reason'),
                  },
                ],
              },
            ]"
            :disabled="!ifCanEdit"
          ></a-textarea>
        </a-form-item>
      </template>
    </a-form>
    <div class="step-buttons" v-if="!ifStep2">
      <!-- 取消 -->
      <a-button class="mr-[20px]" @click="backList(1)">{{
        $t("app.setting.content-width.fluid2222333")
      }}</a-button>
      <template v-if="!ifDispatch">
        <!-- 上报 - 保存草稿 -->
        <a-button
          type="primary"
          class="mr-[20px]"
          @click="addBreach('draft-submit')"
          v-if="ifCanEdit"
          >{{ $t("user.register-result.view-mailbox") }}</a-button
        >
        <!-- 确认上报 -->
        <a-button
          type="primary"
          :loading="btnLoading"
          @click="addBreach('submit')"
          v-if="ifCanEdit"
          >{{ $t("breach.steps.step1.content.submit") }}</a-button
        >
      </template>
      <template v-else>
        <!-- 分配 - 保存草稿 -->
        <a-button
          type="primary"
          class="mr-[20px]"
          @click="addBreach('draft-patch')"
          v-if="ifCanEdit"
          >{{ $t("breach.steps.step2.business.form.buttons.save") }}</a-button
        >
        <!-- 关闭事件 -->
        <a-button
          v-if="ifClose && breachDetail.EventStatus === 3"
          :disabled="!ifCanEdit"
          :loading="btnLoading"
          type="primary"
          @click="addBreach('close')"
        >
          {{ $t("breach.steps.step1.content.buttons.close") }}
        </a-button>
        <!-- 提交 -->
        <a-button
          v-if="!ifClose && breachDetail.EventStatus === 3"
          :disabled="!ifCanEdit"
          :loading="btnLoading"
          type="primary"
          @click="addBreach('select')"
        >
          {{ $t("user.verification-code.required11156611048") }}
        </a-button>
        <!-- 撤回 -->
        <a-button
          type="primary"
          v-if="breachDetail.EventStatus === 2"
          @click="addBreach('reback')"
          >{{
            $t("user.verification-code.required11156611057737144227")
          }}</a-button
        >
      </template>
    </div>
    <a-modal v-model="visible" :closable="false">
      <template v-if="modalType === 'submit'">
        {{ $t("breach.steps.step1.content.submit.tip1") }}<br />
        {{ $t("breach.steps.step1.content.submit.tip2") }}<br />
        {{ $t("breach.steps.step1.content.submit.tip3") }}
      </template>
      <template v-else>
        {{ $t(tipMap[modalType]) }}
      </template>
      <template slot="footer">
        <a-button type="primary" @click="closeModal">{{
          `${$t("app.setting.content-width.fluid2222")}(${count}s)`
        }}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import step1Dlp from "./step1Dlp.vue";
import uploadFile from "@/components/uploadFile/index.vue";
import { whereList } from "@/staticLists/breach";
import { createDataBreach, createFile } from "@/api/dataBreach/json";
import { configurationSelect } from "@/api/configs";
import {
  createLog,
  createReport,
  getProcessorList,
  initActionList,
  reback,
} from "@/api/dataBreach/form";
export default {
  name: "step1",
  props: [
    "breachMode",
    "lang",
    "breachDetail",
    "ifCanEdit",
    "ifDispatch",
    "ifStep2",
  ],
  components: { step1Dlp, uploadFile },
  data() {
    return {
      form: this.$form.createForm(this),
      interval: {},
      count: 5,
      visible: false,
      handlerList: [],
      typeList: [],
      whereList,
      ifClose: false,
      modalType: "",
      EventDestination: undefined,
      tipMap: {
        select: "breach.steps.step1.content.select.tip",
        reback: "breach.steps.step1.content.reback.tip",
      },
      btnLoading: false
    };
  },
  created() {
    if (this.ifDispatch) {
      this.getDispathLists();
    }
  },
  watch: {
    breachDetail: {
      handler(newVal) {
        let resVal = { ...newVal };
        resVal.EventType =
          resVal.EventType === 0 ? undefined : resVal.EventType;
        resVal.EventDestination =
          resVal.EventDestination === 0 ? undefined : resVal.EventDestination;
        this.EventDestination = resVal.EventDestination;
        resVal.EventClose = resVal.EventClose === 0 ? 2 : resVal.EventClose;
        resVal.EventProcessed =
          resVal.EventProcessed === 0 ? undefined : resVal.EventProcessed;
        this.form.setFieldsValue(resVal);
        this.ifClose = resVal.EventClose === 1;
        this.$nextTick(() => {
          this.form.setFieldsValue(resVal);
        });
      },
      immediate: true,
    },
    lang: {
      handler() {
        this.getTypeList();
      },
      immediate: true,
    },
  },
  methods: {
    moment,
    backList(type) {
      if (!type) {
        this.$emit("changeIfFlag", true);
      }
      this.$router.push("/breach/list");
    },
    async addBreach(type, ifBack = true) {
      this.modalType = type;
      let listData = this.$refs.step1Dlp?.listData || [];
      listData.forEach((item) => {
        if (item.Id > 100000000) {
          item.Id = undefined;
        }
      });
      let tempValue = { ...this.form.getFieldsValue() };
      tempValue.EventOccurrenceTime = tempValue.EventOccurrenceTime
        ? moment(tempValue.EventOccurrenceTime).format("YYYY-MM-DD HH:mm:ss")
        : undefined;
      tempValue.EventFindTime = tempValue.EventFindTime
        ? moment(tempValue.EventFindTime).format("YYYY-MM-DD HH:mm:ss")
        : undefined;
      if (type.includes("draft")) {
        // 不做校验 直接保存
        let res = await createDataBreach({
          Id: Number(this.$route.query.Id) || this.breachDetail?.Id,
          EventStatus: this.breachDetail?.Id
            ? this.breachDetail.EventStatus
            : 1,
          ...tempValue,
          SupplementDetailArr: listData,
        });
        let BreachFileArr = this.$refs.uploadFile.listData.filter(
          (item) => item.ifNew
        );
        BreachFileArr.forEach((element) => {
          element.Id = undefined;
          element.BreachId =
            Number(this.$route.query.Id) || this.breachDetail?.Id;
          element.InfoType = 1;
        });
        BreachFileArr.length ? (res = await createFile({ BreachFileArr })) : "";
        if (res.code === 1 && ifBack) this.backList();
      } else if (type !== "reback") {
        // 确认上报/关闭事件/提交
        this.form.validateFields(async (err, value) => {
          if (!err) {
            this.btnLoading = true
            if (listData && !listData.length && this.modalType === 2) {
              this.$message.error(
                this.$t("breach.steps.step1.content.form.table.tip")
              );
              return;
            }
            // 结构：[key, 对应中英文, 是否需要判断邮箱格式, 0:选择/1:填写]
            let keys = [
              [
                "SupplementDetailName",
                "breach.steps.step1.content.form.table.name",
                0,
                0,
              ],
              [
                "SupplementDetailEmail",
                "breach.steps.step1.content.form.table.email",
                1,
                1,
              ],
              [
                "SupplementDetailPersonnelId",
                "breach.steps.step1.content.form.table.userid",
                0,
                1,
              ],
              [
                "SupplementDetailResponsibleEmail",
                "breach.steps.step1.content.form.table.leader",
                1,
                1,
              ],
            ];
            if (listData) {
              for (let i = 0; i < listData.length; i++) {
                for (let j = 0; j < keys.length; j++) {
                  if (!listData[i][keys[j][0]]) {
                    this.$message.error(
                      `${this.$t(
                        keys[j][3]
                          ? "breach.steps.step1.content.form.tip"
                          : "breach.steps.step1.content.form.tip1"
                      )}${this.lang ? "" : " "}${this.$t(keys[j][1])}`
                    );
                    return;
                  } else if (keys[j][2]) {
                    var emailReg =
                      /^[\w\s]{1,}(\.\w+)*@[A-z0-9\-]+(\.[A-z\-]{2,30}){1,2}$/;
                    if (!emailReg.test(listData[i][keys[j][0]])) {
                      this.$message.error(
                        `${
                          this.lang
                            ? ""
                            : this.$t(
                                "breach.steps.step1.content.form.table.tip.bef"
                              ) + " "
                        }${this.$t(keys[j][1])}${
                          (this.lang ? "" : " ") +
                          this.$t(
                            "breach.steps.step1.content.form.table.tip.aft"
                          )
                        }`
                      );
                      return;
                    }
                  }
                }
              }
            }
            if (type === "submit" || type === "select") {
              // 确认上报/提交
              let res = await createDataBreach({
                Id: Number(this.$route.query.Id) || this.breachDetail?.Id,
                EventStatus: type === "submit" ? 3 : 2,
                ...tempValue,
                SupplementDetailArr: listData,
              });
              let BreachFileArr = this.$refs.uploadFile.listData.filter(
                (item) => item.ifNew
              );
              BreachFileArr.forEach((element) => {
                element.Id = undefined;
                element.BreachId =
                  Number(this.$route.query.Id) || this.breachDetail?.Id;
                element.InfoType = 1;
              });
              BreachFileArr.length
                ? (res = await createFile({ BreachFileArr }))
                : "";
              if (res.code === 1) {
                this.openTip();
                if (type === "submit") {
                  // 初始化绑定action列表
                  initActionList({
                    BreachId:
                      this.breachDetail?.Id || Number(this.$route.query.Id),
                  });
                } else {
                  // 存log信息
                  createLog({
                    BreachId: this.breachDetail?.Id,
                    LogUserId: this.$store.state.user.info.YtId,
                    LogUserName: this.$store.state.user.info.YtAdminUserName,
                    LogOperation: `${
                      this.$store.state.user.info.YtAdminUserName
                    }分配给${this.$t(
                      this.handlerList.filter(
                        (item) =>
                          item.value ===
                          this.form.getFieldValue("EventProcessed")
                      )[0]?.label
                    )}`,
                  });
                }
              }
            } else {
              // 关闭事件
              let res = await createDataBreach({
                Id: Number(this.$route.query.Id) || this.breachDetail?.Id,
                EventStatus: 5,
                ...tempValue,
                SupplementDetailArr: listData,
              });
              if (res.code === 1) {
                // 生成报告
                for (let index = 1; index < 3; index++) {
                  createReport({
                    Id: this.breachDetail.Id,
                    lang: index,
                  });
                }
                this.closeModal();
                this.backList();
              }
            }
            this.btnLoading = false
          }
        });
      } else {
        // 撤回
        let res = await reback({ Id: this.breachDetail?.Id });
        if (res.code === 1) this.openTip();
      }
    },
    closeModal() {
      clearInterval(this.interval);
      this.visible = false;
      this.count = 5;
      this.backList();
    },
    async getDispathLists() {
      let { data } = await getProcessorList();
      let ifAdd = true;
      data.forEach((item) => {
        if (item.value === this.breachDetail.EventProcessed) {
          ifAdd = false;
        }
      });
      this.handlerList = ifAdd
        ? [
            {
              label: this.breachDetail.EventProcessedStr,
              value: this.breachDetail.EventProcessed,
            },
            ...data,
          ]
        : data;
      this.getTypeList();
    },
    async getTypeList() {
      // 风险类型
      const { data: riskType } = await configurationSelect({
        state: 9,
        types: this.lang ? 0 : 1,
      });
      this.typeList = riskType;
    },
    openTip() {
      this.visible = true;
      this.interval = setInterval(() => {
        if (!--this.count) {
          this.closeModal();
        }
      }, 1000);
    },
  },
};
</script>

<style>
</style>